package com.qdxwx.manage.controller.picture;

import com.qdxwx.common.config.UploadConfig;
import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.page.PageRequest;
import com.qdxwx.common.page.TableDataInfo;
import com.qdxwx.common.upload.UploadState;
import com.qdxwx.common.upload.UploadUtils;
import com.qdxwx.common.utils.ImageUtils;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.data.service.channel.ChannelService;
import com.qdxwx.data.service.member.MemberTypeService;
import com.qdxwx.data.service.picture.PictureAlbumService;
import com.qdxwx.data.service.picture.PictureService;
import com.qdxwx.common.annotation.Permissions;
import com.qdxwx.manage.controller.BaseController;

import com.qdxwx.manage.support.SessionUtils;
import com.qdxwx.models.manager.Manager;
import com.qdxwx.models.picture.Picture;
import com.qdxwx.models.picture.PictureAlbum;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import jakarta.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import java.util.List;

/**
 * 图片专辑内容管理Controller
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
@Controller
@RequestMapping("/picture/album/item")
public class PictureAlbumItemController extends BaseController {

    @Autowired
    private PictureAlbumService pictureAlbumService;
    @Autowired
    private PictureService pictureService;
    @Autowired
    private MemberTypeService memberTypeService;
    @Autowired
    private ChannelService channelService;

    @Permissions("picture:album:item")
    @GetMapping("/list.html")
    public String list(HttpServletRequest request, ModelMap mmap) {
        int id = TKConvert.toInteger(request.getParameter("id"));
        if (id < 1) return error404;
        PictureAlbum pictureAlbum = pictureAlbumService.get(id);
        if (pictureAlbum == null) return error404;
        mmap.put("pictureAlbum", pictureAlbum);
        mmap.put("channel", channelService.get(pictureAlbum.getChannelId()));
        return "picture/picture-album-item-list";
    }

    @PostMapping("/list.json")
    @ResponseBody
    public TableDataInfo list(HttpServletRequest request) {
        int albumId = TKConvert.toInteger(request.getParameter("albumId"));
        List<Picture> list = pictureService.getListByAlbumId(albumId, PageRequest.form(request));
        int count = pictureService.countByAlbumId(albumId);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(list);
        rspData.setTotal(count);
        return rspData;
    }

    @Permissions("picture:album:item")
    @GetMapping("/add.html")
    public String add(HttpServletRequest request, ModelMap mmap) {
        Manager manager = SessionUtils.getManager();
        if (manager == null) return error404;
        int albumId = TKConvert.toInteger(request.getParameter("albumId"));
        if (albumId < 1) return error404;
        PictureAlbum pictureAlbum = pictureAlbumService.get(albumId);
        if (pictureAlbum == null) return error404;
        mmap.put("pictureAlbum", pictureAlbum);
        mmap.put("channel", channelService.get(pictureAlbum.getChannelId()));
        mmap.put("memberTypes", memberTypeService.getList());
        return "picture/picture-album-item-add";
    }

    @Permissions("picture:album:item")
    @RequestMapping("/upload.json")
    @ResponseBody
    public AjaxResult ImgAdd(HttpServletRequest request, @RequestParam("file") MultipartFile[] imgfile) {
        Manager manager = SessionUtils.getManager();
        if (manager == null) return AjaxResult.error("登录超时");
        int albumId = TKConvert.toInteger(request.getParameter("albumId"));
        if (albumId < 1) return AjaxResult.error("参数异常，albumId=" + albumId);
        PictureAlbum pictureAlbum = pictureAlbumService.get(albumId);
        if (pictureAlbum == null) return AjaxResult.error("找不到专辑");
        logger.info("albumId:" + albumId);
        if (imgfile == null || imgfile.length < 1) {
            return AjaxResult.error("没有检测到文件！");
        }
        try {
            int count = pictureAlbumService.countItem(albumId);
            for (MultipartFile multipartFile : imgfile) {
                count += 1;
                UploadState uploadState = UploadUtils.saveImageFile(multipartFile, UploadConfig.uploadImageFolder);
                if (uploadState.getCode() != 0) {
                    return AjaxResult.error(uploadState.getMsg());
                }
                String imgUrl = uploadState.getSavePath();
                String fileExt = UploadUtils.getFileExt(imgUrl);
                String viewUrl = UploadUtils.getSavePath(UploadConfig.uploadPreviewFolder, fileExt, manager.getUserId());
                //水印图片地址
                InputStream water = this.getClass().getClassLoader().getResourceAsStream("static/img/logo-water.png");
                ImageUtils.press(UploadConfig.uploadRoot + imgUrl, UploadConfig.uploadRoot + viewUrl, ImageIO.read(water), 0.5f);
                BufferedImage sourceImg = ImageIO.read(new File(UploadConfig.uploadRoot + imgUrl));
                if (sourceImg == null) {
                    return AjaxResult.error("该文件不是图片");
                }
                //计算封面图尺寸
                int coverHeight = sourceImg.getHeight();
                int coverWidth = sourceImg.getWidth();
                //  if(coverHeight > 350) {
                coverHeight = 350;
                // }
                //  if(coverWidth > 500) {
                coverWidth = 500;
                // }
                //封面图地址
                String coverPath = UploadUtils.getSavePath(UploadConfig.uploadCoverFolder, fileExt, manager.getUserId());
                ImageUtils.zoomWithCut(UploadConfig.uploadRoot + imgUrl, UploadConfig.uploadRoot + coverPath, coverWidth, coverHeight);
                Picture picture = new Picture();
                picture.setTitle(pictureAlbum.getTitle() + "(" + count + ")");
                picture.setChannelId(pictureAlbum.getChannelId());
                picture.setCategoryId(pictureAlbum.getCategoryId());
                picture.setCategoryName(pictureAlbum.getCategoryName());
                picture.setSubjectId(pictureAlbum.getSubjectId());
                picture.setLevelId(TKConvert.toInteger(request.getParameter("levelId")));
                picture.setPrice(Double.valueOf(TKConvert.toDouble(request.getParameter("price"), 0.0) * 100).intValue());
                picture.setCoverUrl(coverPath);
                picture.setViewUrl(viewUrl);
                picture.setImgUrl(imgUrl);
                picture.setFileSize(uploadState.getFileSize());
                picture.setFileExt(imgUrl.substring(imgUrl.lastIndexOf(".") + 1).toLowerCase());
                picture.setImgWidth(sourceImg.getWidth());
                picture.setImgHeight(sourceImg.getHeight());
                picture.setImgDpi(0);
                picture.setStatus(1);
                picture.setUserId(manager.getUserId());
                picture.setUserName(manager.getManagerName());
                int row = pictureService.insert(picture);
                if (row > 0) {
                    pictureAlbumService.insertItem(pictureAlbum.getId(), picture.getId());
                }
            }
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("上传出现异常！异常出现在");
        }
    }

    @Permissions("picture:album:item")
    @PostMapping("/remove.json")
    @ResponseBody
    public AjaxResult itemRemove(HttpServletRequest request, ModelMap mmap) {
        Manager manager = SessionUtils.getManager();
        if (manager == null) return AjaxResult.forbid();
        int albumId = TKConvert.toInteger(request.getParameter("albumId"));
        int pictureId = TKConvert.toInteger(request.getParameter("pictureId"));
        if (albumId < 1 || pictureId < 1) return AjaxResult.error("参数错误！");
        pictureAlbumService.deleteItem(albumId, pictureId);
        return AjaxResult.success();
    }
}
